package com.jiyun.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jiyun.dto.FindTeamList;
import com.jiyun.dto.TeamDoctor;
import com.jiyun.model.information.MiddleTeamDoctor;
import com.jiyun.model.information.ZlDoctor;
import com.jiyun.model.information.ZlTeam;
import com.jiyun.result.Result;
import com.jiyun.service.IMiddleTeamDoctorService;
import com.jiyun.service.IZlTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-09-22
 */
@RestController
@RequestMapping("/team/")
@Api("团队管理")
@Slf4j
public class ZlTeamController {

    @Autowired
    private IZlTeamService zlTeamService;

    @Autowired
    private IMiddleTeamDoctorService middleTeamDoctorService;

    @Autowired
    private IMiddleTeamDoctorService iMiddleTeamDoctorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiModelProperty("团队管理分页查询接口（根据名称和地址模糊查询）")
    @RequestMapping("findPage/{pn}/{ps}")
    public Result findPage(@PathVariable Integer pn, @PathVariable Integer ps, @RequestBody ZlTeam zlTeam) {
//        log.info("条件查询：" + zlTeam);
        IPage<ZlTeam> page = zlTeamService.findPage(pn, ps, zlTeam);
        Object o = redisTemplate.opsForValue().get("jg");
        String str = (String) o;
//        删除这条数据，防止多次拿到
        redisTemplate.delete("jg");
        log.info("监听到了：" + str);
        FindTeamList findTeamList = new FindTeamList();
        findTeamList.setTeamIPage(page).setStr(str);
        return Result.ok(findTeamList);
    }

    //    状态变更
    @ApiModelProperty("修改状态")
    @RequestMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable String status) {
//        log.info("修改状态：" + id + "--" + status);
        ZlTeam byId = zlTeamService.getById(id);
        byId.setStatus(status);
        zlTeamService.updateById(byId);
        return Result.ok();
    }

    @ApiModelProperty("查询所有")
    @RequestMapping("findTeam")
    public Result findDoctor() {
        return Result.ok(zlTeamService.list());
    }


    @ApiModelProperty("查看某个机构有哪些团队")
    @RequestMapping("findTid/{id}")
    public Result findTid(@PathVariable Integer id) {
//        System.err.println("机构id"+id);
        List<ZlTeam> tid = zlTeamService.findTeam(id);
//        log.info("查看机构有哪些团队：" + tid);
        return Result.ok(tid);
    }

    //团队医生信息查询
    @ApiModelProperty("团队医生信息查询")
    @RequestMapping("findTeamDoctor")
    public Result findDoctor(@RequestBody ZlTeam zlTeam) {
        log.info("团队医生信息查询：" + zlTeam);                     // 团队id ，机构id
        List<ZlDoctor> doctorList1 = zlTeamService.findTeamDoctor(zlTeam);
        //查询申请加入团队的医生
        List<ZlDoctor> doctorList2 = zlTeamService.findTeamDoctor2(zlTeam);
        TeamDoctor teamDoctor = new TeamDoctor();
        teamDoctor.setZlDoctor1(doctorList1).setZlDoctor2(doctorList2);
//        return Result.ok(doctorList1);
        return Result.ok(teamDoctor);
    }
    @ApiModelProperty("根据ID查询")
    @RequestMapping("get/{id}")
    public ZlTeam getById(@PathVariable Integer id) {
        ZlTeam byId = zlTeamService.getById(id);
        log.info("查询结果：" + byId);
        return byId;
    }
//    @ApiModelProperty("机构id查询团队")
//    public List<ZlTeam> findTeamByiId(Integer id) {
//        List<ZlTeam> teamByiId = zlTeamService.findJidTeam(id);
//        return teamByiId;
//    }

    @ApiModelProperty("医生申请加入团队不通过")
    @RequestMapping("jujue/{id}/{tid}")
    private Result jujue(@PathVariable Integer id, @PathVariable Integer tid) {
        middleTeamDoctorService.remove(new QueryWrapper<MiddleTeamDoctor>()
                .eq("did", id)
                .eq("tid", tid));
        return Result.ok("已拒绝");
    }

    @ApiModelProperty("医生申请加入团队通过")
    @RequestMapping("tongguo/{id}/{tid}")
    private Result tongguo(@PathVariable Integer id, @PathVariable Integer tid) {
//      团队成员数量加1
        ZlTeam byId = zlTeamService.getById(tid);
        byId.setMemberCount(byId.getMemberCount() + 1);
        zlTeamService.updateById(byId);

        MiddleTeamDoctor middleTeamDoctor = middleTeamDoctorService.getOne(new QueryWrapper<MiddleTeamDoctor>()
                .eq("did", id).eq("tid", tid));
        if (middleTeamDoctor == null) {
            new RuntimeException("未找到该医生");
        }
        middleTeamDoctor.setStatus(1);
        middleTeamDoctorService.updateById(middleTeamDoctor);
        return Result.ok("通过成功");
    }


    //解散团队
    @Transactional
    @ApiModelProperty("解散团队")
    @RequestMapping("deleteTeam/{id}")
    public Result deleteTeam(@PathVariable Integer id) {
//        要解散的团队
        ZlTeam team = zlTeamService.getById(id);
        System.err.println("团队信息" + team);
        String tt = team.getName();
//        查询团队里面的医生成员
        List<ZlDoctor> doctorList = zlTeamService.findTeamDoctorByiId(id);
//        System.err.println(doctorList);
        String names = doctorList.stream()
                .map(ZlDoctor::getDoctorName)
                .reduce((name1, name2) -> name1 + ", " + name2)
                .orElse("");

//      打印结果
        System.err.println(names.toString());
        String dd = names + " ---- " + tt + "解散了";
//        医生管理页面通知，，，MQ消息
        rabbitTemplate.convertAndSend("pei.lin", dd);
//        团队表删除
        zlTeamService.removeById(id);
//        中间表删除该团队
        middleTeamDoctorService.remove(new QueryWrapper<MiddleTeamDoctor>().eq("tid",id));

        return Result.ok(tt + "解散了");
    }


    @RequestMapping("dd")

    public Result dd(@RequestHeader String token){
//        rabbitTemplate.convertAndSend("pei.lin","解散了7777777777777");
        System.out.println("token:"+ token);
        return Result.ok();
    }
//    @RabbitListener(queuesToDeclare = @Queue("pei.lin"))
//    public void yy(String str) {
//        System.err.println(str+"监听");
//    }

    @ApiModelProperty("接收机构倒闭的消息")
    @RabbitListener(queuesToDeclare = @Queue("pei.jy"))
    public void jsTeam(String str) {
        log.info("接收到消息：" + str);
        redisTemplate.opsForValue().set("jg", str);
    }


}
